package com.yang.task;

import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import com.yang.config.NoteListConfig;
import com.yang.entity.*;
import com.yang.service.*;
import com.yang.utils.SendEmailUtils;
import com.yang.utils.SendTelUtils;
import com.yang.utils.UtilsFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yangdacheng
 * @title: SendEmailTask 自动发送邮件提示
 * @projectName note_api
 * @description: TODO
 * @date 2022/3/9 9:55 下午
 */
@Component
@Slf4j
public class SendEmailTask {

    @Resource
    private NoteUserService userService; //用户服务类
    @Resource
    private NoteThingsService noteThingsService; //事件服务类
    @Resource
    private UserThingsService userThingsService; //用户事件服务类
    @Resource
    private NoteEmailService noteEmailService; //成功发送同时服务类
    @Resource
    private UserNoteInfoService userNoteInfoService; //用户剩余短信服务类
    @Resource
    private EmailTemplateServer emailTemplateServer; //邮箱模板
    @Resource
    private SendEmailUtils sendEmailUtils;  //发送邮箱服务
    @Resource
    private SendTelUtils sendTelUtils;  //发送短信服务
    @Resource
    private UtilsFactory utilsFactory; //工具工程
    @Resource
    private NoteListConfig noteListConfig;  //系统信息
    private List<NoteThings> noteThings = new ArrayList<>();
    private EmailTemplate emailTemplate = null; //获取模板信息
    private String telTemplate = "您的任务:{1}将于{2}开始请不要忘记哟～";// 短信模板
    private NoteEmail noteEmail = null; //添加短信实体类

    /**
     * 获取未打卡的数据 每1分钟获取 对应的数据并且存放到集合中
     */
    @Scheduled(cron = "0 0/1 * * * *")
    public void getNoPunch() {
        log.info("获取事件集合");
        noteThings = noteThingsService.queryAllThingNoPunch(); //获取今天未打卡的数据
        log.info("集合的大小："+noteThings.size());
    }

    @Scheduled(cron = "0/1 0/1 * * * ? ")
    public void sendTest() {
        emailTemplate = emailTemplateServer.getTemplateByID("10001");
        //遍历集合
        if (!noteThings.isEmpty()){
            for(int index=0;index<noteThings.size();){
                log.info("开始遍历事件");
                //判断距离用户的事件开始是否只有5分钟了
                try {
                    if ((utilsFactory.dateFormat(noteThings.get(index).getStartTime(),
                            "yyyy-MM-dd HH:mm:ss").getTime() - System.currentTimeMillis()) / (1000 * 60) <= 5) {
                        NoteUser noteUser = userService.queryUserByID(userThingsService.queryThingsByTID(
                                noteThings.get(index).getThingsId()).getUserid()); //获取用户信息
                        UserNoteInfo userNoteInfo = userNoteInfoService.queryUserNoteByUid(noteUser.getUserid());
                        try {
                            //发送短信
                            //判断开启了短信发送并且发送数量充足
                            if (noteThings.get(index).getIsTelStart() != 0 && userNoteInfo.getNoteResidue()>0) {
                                String telCache = telTemplate;
                                String[] templateParamSet = {noteThings.get(index).getThingsName(),noteThings.get(index).getStartTime().split(" ")[1]};
                                SendStatus sendStatus = sendTelUtils.SendCode("1328972", noteUser.getUserTel(), templateParamSet);
                                if ("send success".equals(sendStatus.getMessage())) {
                                    //发送成功 修改用户剩余发送数量
                                    userNoteInfo.setNoteResidue(userNoteInfo.getNoteResidue() - 1);
                                    userNoteInfoService.updateUserNote(userNoteInfo);
                                    noteEmail = new NoteEmail(utilsFactory.buildID(), new Date(), 1,
                                            telCache.replace("{1}", noteThings.get(index).getThingsName()).replace("{2}", noteThings.get(index).getStartTime()),
                                            noteUser.getUserid(), 1);
                                    noteEmailService.insertNoteEmail(noteEmail); //添加到数据库
                                    log.info(noteUser.getName() + "发送短信成功");
                                }
                            }else{
                                log.info("短信剩余数量不足....");
                            }

                            //发送邮件
                            if (noteThings.get(index).getIsEmailStart() != 0) {
                                EmailTemplate templateCache = emailTemplate;
                                templateCache.setTestTemplate(templateCache.getTestTemplate().
                                        replace("{1}", noteListConfig.getAppTitle())
                                        .replace("{2}", noteThings.get(index).getThingsName())
                                        .replace("{3}", noteThings.get(index).getStartTime()));
                                sendEmailUtils.sendCode(noteUser.getUserEmail(),
                                        templateCache.getTestTemplate(),
                                        noteListConfig.getAppTitle());
                                noteEmail = new NoteEmail(utilsFactory.buildID(), new Date(), 1,
                                        emailTemplate.getTestTemplate(), noteUser.getUserid(), 0);
                                noteEmailService.insertNoteEmail(noteEmail); //添加到数据库
                                log.info(noteUser.getName() + "发送邮箱成功");
                            }
                        } finally {
                            noteThings.get(index).setIsSend(1); //改变状态为  发送成功
                            noteThingsService.updateNoteThings(noteThings.get(index)); //修改服务
                            noteThings.remove(index); //移除当前对象
                        }
                        Thread.sleep(1000 * 2); //休眠2秒
                    } else {
                        log.info("任务休眠20秒");
                        Thread.sleep(1000 * 20);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    noteEmail = null;
                }
            }

        }
    }
}
